package com.asen.commons.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用配置
 *
 * @author Gary
 * @version 1.0
 * @date 2020-05-26
 */
@Configuration
public class RestTemplateConfig {

    public static final String REST_TEMPLATE = "restTemplate";

    public static final String COMMON_REST_TEMPLATE = "commonRestTemplate";

    public static final String API_REST_TEMPLATE = "apiRestTemplate";

    @LoadBalanced
    @Bean(COMMON_REST_TEMPLATE)
    public RestTemplate commonRestTemplate(RestTemplateBuilder restTemplateBuilder) {
        restTemplateBuilder.setConnectTimeout(Duration.ofMinutes(10));
        restTemplateBuilder.setReadTimeout(Duration.ofMinutes(10));
        return restTemplateBuilder.build();
    }

    @Primary
    @LoadBalanced
    @Bean(REST_TEMPLATE)
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        restTemplateBuilder.setConnectTimeout(Duration.ofMinutes(10));
        restTemplateBuilder.setReadTimeout(Duration.ofMinutes(10));
        return restTemplateBuilder.build();
    }

    @Bean(API_REST_TEMPLATE)
    public RestTemplate apiRestTemplate(RestTemplateBuilder restTemplateBuilder) {
        restTemplateBuilder.setConnectTimeout(Duration.ofMinutes(10));
        restTemplateBuilder.setReadTimeout(Duration.ofMinutes(10));

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(mediaTypes);
        restTemplateBuilder.additionalMessageConverters(converter);

        RestTemplate restTemplate = restTemplateBuilder.build();

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(converter);
        restTemplate.setMessageConverters(messageConverters);
        return restTemplate;
    }

}
